package com.zrf.gulimall.cart.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.zrf.gulimall.cart.dto.CartItemDto;
import com.zrf.gulimall.cart.feign.ProductFeignService;
import com.zrf.gulimall.cart.interceptor.CartInterceptor;
import com.zrf.gulimall.cart.service.ShopCartService;
import com.zrf.gulimall.cart.to.UserInfoTo;
import com.zrf.gulimall.cart.vo.CartItemVo;
import com.zrf.gulimall.cart.vo.CartVo;
import com.zrf.gulimall.cart.vo.SkuInfoVo;
import com.zrf.gulimall.commnon.core.exception.CustomException;
import com.zrf.gulimall.commnon.core.response.Resp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.zrf.gulimall.cart.constant.CartConstant.CART_PREFIX;

/**
 * @Author zhanrf
 * @Date 2022/1/2 23:43
 */
@Service
public class ShopCartServiceImpl implements ShopCartService {
	@Resource
	private RedisTemplate redisTemplate;

	@Autowired
	private ProductFeignService productFeignService;

	@Autowired
	private ThreadPoolExecutor executor;

	@Override
	public void addCartItem(Long skuId, Integer num) {
		// 拿到要操作的购物车信息
		BoundHashOperations<String, String, String> cartOps = getCartOps();
		//判断Redis是否有该商品的信息
		String productRedisValue = cartOps.get(skuId.toString());
		// 如果没有就添加数据，为保持数据一致性，只保存skuId和num，查看时再去远程调用商品服务商品信息
		if (StrUtil.isEmpty(productRedisValue)) {
			//2、添加新的商品到购物车(redis)
			CartItemDto cartItemDto = new CartItemDto();
			cartItemDto.setSkuId(skuId);
			cartItemDto.setCount(num);
			String cartItemJson = JSON.toJSONString(cartItemDto);
			cartOps.put(skuId.toString(), cartItemJson);
		} else {
			//购物车有此商品，修改数量即可
			CartItemDto cartItemDto = JSON.parseObject(productRedisValue, CartItemDto.class);
			cartItemDto.setCount(cartItemDto.getCount() + num);
			// 修改redis的数据
			String cartItemJson = JSON.toJSONString(cartItemDto);
			cartOps.put(skuId.toString(), cartItemJson);
		}
	}

	@Override
	public CartItemVo getCartItem(Long skuId) {
		//拿到要操作的购物车信息，查询出购物车信息
		BoundHashOperations<String, String, String> cartOps = getCartOps();
		String redisValue = cartOps.get(skuId.toString());
		CartItemDto cartItemDto = JSON.parseObject(redisValue, CartItemDto.class);
		if (Objects.isNull(cartItemDto)) {
			throw new CustomException("购物车不存在该商品！");
		}
		// 返回前端商品信息
		CartItemVo cartItemVo = new CartItemVo();
		cartItemVo.setCheck(cartItemDto.getCheck());
		//开启第一个异步任务
		CompletableFuture<Void> getSkuInfoFuture = CompletableFuture.runAsync(() -> {
			//1、远程查询当前要添加商品的信息
			Resp<SkuInfoVo> productSkuInfo = productFeignService.getSkuInfo(skuId);
			SkuInfoVo skuInfo = productSkuInfo.getData();
			//数据赋值操作
			cartItemVo.setSkuId(skuInfo.getSkuId());
			cartItemVo.setTitle(skuInfo.getSkuTitle());
			cartItemVo.setImage(skuInfo.getSkuDefaultImg());
			cartItemVo.setPrice(skuInfo.getPrice());
			cartItemVo.setCount(cartItemDto.getCount());
		}, executor);
		//开启第二个异步任务
		CompletableFuture<Void> getSkuAttrValuesFuture = CompletableFuture.runAsync(() -> {
			//2、远程查询skuAttrValues组合信息
			List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
			cartItemVo.setSkuAttrValues(skuSaleAttrValues);
		}, executor);
		//等待所有的异步任务全部完成
		CompletableFuture.allOf(getSkuInfoFuture, getSkuAttrValuesFuture).join();
		return cartItemVo;
	}

	@Override
	public CartVo getCart() {
		CartVo cartVo = new CartVo();
		List<CartItemDto> cartItems;
		UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();
		if (userInfoTo.getUserId() != null) {
			// 如果临时购物车的数据还未进行合并
			List<CartItemDto> tempCartItems = getCartItems(CART_PREFIX + userInfoTo.getUserKey());
			if (CollUtil.isNotEmpty(tempCartItems)) {
				//临时购物车有数据需要进行合并操作
				for (CartItemDto item : tempCartItems) {
					addCartItem(item.getSkuId(), item.getCount());
				}
				//清除临时购物车的数据
				clearCartInfo(CART_PREFIX + userInfoTo.getUserKey());
			}
			// 获取登录后的购物车数据【包含合并过来的临时购物车的数据和登录后购物车的数据】
			cartItems = getCartItems(CART_PREFIX + userInfoTo.getUserId());
		} else {
			//没登录，获取临时购物车里面的所有购物项
			cartItems = getCartItems(CART_PREFIX + userInfoTo.getUserKey());
		}
		// 转为vo
		List<CartItemVo> cartItemVos = cartItems.stream().map(cartItem -> {
			CartItemVo cartItemVo = new CartItemVo();
			cartItemVo.setSkuId(cartItem.getSkuId());
			cartItemVo.setCheck(cartItem.getCheck());
			cartItemVo.setCount(cartItem.getCount());
			return cartItemVo;
		}).collect(Collectors.toList());
		cartVo.setItems(cartItemVos);
		// 为每个vo设置信息和属性
		populate(cartItemVos);
		return cartVo;
	}

	@Override
	public void clearCartInfo(String cartKey) {
		redisTemplate.delete(cartKey);
	}

	@Override
	public void changeItemCount(Long skuId, Integer num) {
		BoundHashOperations<String, String, String> cartOps = getCartOps();
		String s = cartOps.get(skuId.toString());
		if (StrUtil.isNotEmpty(s)) {
			CartItemDto cartItemDto = JSON.parseObject(s, CartItemDto.class);
			cartItemDto.setCount(num);
			cartOps.put(skuId.toString(), JSON.toJSONString(cartItemDto));
			return;
		}
		CartItemDto cartItemDto = new CartItemDto();
		cartItemDto.setSkuId(skuId);
		cartItemDto.setCount(num);
		cartOps.put(skuId.toString(), JSON.toJSONString(cartItemDto));
	}

	@Override
	public void deleteIdCartInfo(Integer skuId) {
		BoundHashOperations<String, String, String> cartOps = getCartOps();
		cartOps.delete(skuId.toString());
	}

	@Override
	public void checkItem(Long skuId, Integer checked) {
		BoundHashOperations<String, String, String> cartOps = getCartOps();
		String s = cartOps.get(skuId.toString());
		if (StrUtil.isNotEmpty(s)) {
			CartItemDto cartItemDto = JSON.parseObject(s, CartItemDto.class);
			cartItemDto.setCheck(checked == 1);
			cartOps.put(skuId.toString(), JSON.toJSONString(cartItemDto));
		}
	}

	@Override
	public List<CartItemVo> getUserCartItems() {
		//获取当前用户登录的信息
		UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();
		//如果用户未登录直接返回null
		if (userInfoTo.getUserId() == null) {
			return CollUtil.newArrayList();
		}
		//获取所有的购物项
		List<CartItemDto> cartItems = getCartItems(CART_PREFIX + userInfoTo.getUserId());
		if (cartItems == null) {
			throw new CustomException("购物项不存在！");
		}
		//筛选出选中的
		List<CartItemVo> cartItemVoList = cartItems.stream()
				.filter(CartItemDto::getCheck)
				.map(item -> {
					CartItemVo cartItemVo = new CartItemVo();
					cartItemVo.setSkuId(item.getSkuId());
					cartItemVo.setCheck(item.getCheck());
					cartItemVo.setCount(item.getCount());
					return cartItemVo;
				})
				.collect(Collectors.toList());
		// 为每个vo设置信息和属性
		populate(cartItemVoList);
		return cartItemVoList;
	}

	/**
	 * 填充属性
	 * @param cartItemVoList 需要填充的对象
	 */
	private void populate(List<CartItemVo> cartItemVoList) {
		// 为每个vo设置信息和属性
		List<Long> skuIdList = cartItemVoList.stream().map(CartItemVo::getSkuId).collect(Collectors.toList());
		// 异步调用获取商品信息
		CompletableFuture<Void> skuInfoFuture = CompletableFuture.runAsync(() -> {
			Resp<List<SkuInfoVo>> resp = productFeignService.getSkuInfoByIds(skuIdList);
			if (resp.getCode() == 0) {
				List<SkuInfoVo> data = resp.getData();
				Map<Long, SkuInfoVo> skuMap = data.stream().collect(Collectors.toMap(SkuInfoVo::getSkuId, Function.identity()));
				cartItemVoList.forEach(cartItem -> {
					SkuInfoVo skuInfo = skuMap.get(cartItem.getSkuId());
					if (Objects.nonNull(skuInfo)) {
						cartItem.setTitle(skuInfo.getSkuTitle());
						cartItem.setImage(skuInfo.getSkuDefaultImg());
						cartItem.setPrice(skuInfo.getPrice());
					}
				});
			}
		}, executor);
		// 异步查询skuAttrValues组合信息
		CompletableFuture<Void> attrFuture = CompletableFuture.runAsync(() -> {
			// todo 远程调用商品服务，查询skuAttrValues组合信息
			cartItemVoList.forEach(cartItem -> {
				cartItem.setSkuAttrValues(CollUtil.newArrayList());
			});
		}, executor);
		CompletableFuture.allOf(skuInfoFuture, attrFuture).join();
	}

	/**
	 * 获取到要操作的购物车
	 */
	private BoundHashOperations<String, String, String> getCartOps() {
		//先得到当前用户信息
		UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();
		String cartKey = CART_PREFIX + userInfoTo.getUserKey();
		if (userInfoTo.getUserId() != null) {
			cartKey = CART_PREFIX + userInfoTo.getUserId();
		}
		//绑定指定的key操作Redis
		BoundHashOperations<String, String, String> operations = redisTemplate.boundHashOps(cartKey);

		return operations;
	}

	/**
	 * 获取购物车里面的数据
	 *
	 * @param cartKey 购物车的key
	 * @return
	 */
	private List<CartItemDto> getCartItems(String cartKey) {
		//获取购物车里面的所有商品
		BoundHashOperations<String, String, String> operations = redisTemplate.boundHashOps(cartKey);
		List<String> values = operations.values();
		if (!CollUtil.isEmpty(values)) {
			return values.stream().map(str -> JSON.parseObject(str, CartItemDto.class)).collect(Collectors.toList());
		}
		return CollUtil.newArrayList();

	}
}
